package fon.test.webservice;

import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;

import org.xml.sax.SAXException;

import android.util.Log;

public class GuGuLog {
	String func_name;
	int version;
	ArrayList result;
	HashMap<String, String> resultMap;
	GGAPIFuncID func_id;
	APIMethod methodNameCaller;
	HashMap<String, String> params;
	
	public GuGuLog(){
		params = new HashMap();
		resultMap = new HashMap();
		this.version=1;
	}
	public void callGuGuLogAPI(String name){
		String methodName = "doAPI";
		this.func_name = name;
		
		try {
			Class cl=Class.forName(this.getClass().getPackage().getName()+"."+name);
			Constructor m[] = cl.getDeclaredConstructors();
			Constructor constructor = m[0];
			//Log.d("gugulog", constructor.toString());
			Object invoker = constructor.newInstance(this.getObjParams());
			methodNameCaller =(APIMethod)invoker;	
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 

	}
	public void AddParam(String key,String value){
		params.put(key, value);
	}
	public HashMap<String,String> getParams(){
		return params;
	}
	public Object[] getObjParams(){
		HashMap map = getParams();
		String param = Enum.valueOf(GGAPIFuncParams.class, func_name).getMethod();
		//Log.d("gugulog",param+"");
		String[] methodParams =param.split(",");
		//Log.d("gugulog",methodParams.length+"");
		Object[] output = new Object[methodParams.length];
		//this loop is gathering the required parameters and wrap as parameter object
		for(int i=0;i<methodParams.length;i++){

			//Currently, first param always return null; Fix first param for func_id;
			if(i==0){
				output[i] = this.getFuncID(func_name);
				Log.d("gugulog","id:"+func_name+" value:"+this.getFuncID(func_name));
			}
			else{
				output[i] = map.get(methodParams[i]);
				Log.d("gugulog","id:"+methodParams[i]+" value:"+map.get(methodParams[i]));
			}
			
		}

		return output;
	}
	
	public ArrayList getArrayResult(){
		result = methodNameCaller.doAPI();
		return result;
	}
	public HashMap<String,String> getResult(int itemNum){
		ArrayList arr = methodNameCaller.doAPI();
		ArrayList header = (ArrayList)arr.get(0);
		ArrayList value = (ArrayList) arr.get(itemNum+1);
		for(int i=0;i<value.size();i++){
			resultMap.put(header.get(i).toString(), value.get(i).toString());
			
			//Log.d("gugulog","resultMap: "+header.get(0).toString()+" ");
		}
		
		return resultMap;
	}
	
	public int getFuncID(String str){
		return Enum.valueOf(GGAPIFuncID.class, str).getId();
	}
	public int getCurrentFuncID(){
		
		return getFuncID(this.func_name);
	}
	public String getXML(){
		
		return methodNameCaller.getXML();
	}

}
